/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.account.controller.member;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.account.entity.Payment;
import com.rzico.account.entity.Refunds;
import com.rzico.account.service.PaymentService;
import com.rzico.account.service.RefundsService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Member;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.MemberService;
import com.rzico.core.entity.SysMch;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.PaymentPlugin;
import com.rzico.core.service.SysMchService;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 退款单控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "退款单接口")
@RestController
@RequestMapping("/member/refunds")
public class RefundsMemberController extends BaseController {

    @Autowired
    private RefundsService refundsService;

    @Autowired
    private SysPluginService sysPluginService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private PaymentService paymentService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysMchService sysMchService;


    /**
     * 我的退款记录
     *
     * @return
     */
    @ApiOperation("我的退款记录")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query")
    })
    public CommResult<Payment> list(String startDate, String endDate, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(startDate)){
            params.put("startDate", startDate);
        }
        if (StringUtils.isNotEmpty(endDate)){
            params.put("endDate", endDate);
        }
        Member member = memberService.getCurrent();
        if (member!=null) {
            params.put("memberId", member.getId());
        } else {
            return CommResult.error("没有登录");
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Refunds> list = refundsService.selectList(params);
        PageResult<Refunds> pageResult = new PageResult<Refunds>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }


    /**
     * 发起退款
     *
     * @param sn
     * @return
     */
    @Log(desc = "发起退款", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("发起退款")
    @PostMapping("/submit")
    public CommResult<Payment> submit(String sn, String paymentPluginId, HttpServletRequest request) {

        Refunds refunds = refundsService.findBySn(sn);
        if (refunds==null) {
            return CommResult.error("无效付款单号");
        }

        Enterprise enterprise = enterpriseService.findById(refunds.getEnterpriseId());


        SysMch sysMch = sysMchService.selectByPrimaryKey(enterprise.getMchId());
        if (sysMch.getMchType().equals(2) || sysMch.getMchType().equals(1)) {
            //特约商户,服务商代收
            enterprise = enterpriseService.findByMch(sysMch.getIsvId());
        }

        SysPlugin sysPlugin = sysPluginService.getEnabledPlugin(enterprise.getMchId(),paymentPluginId);
        if (sysPlugin==null) {
            return CommResult.error("无效插件编号");
        }

        PaymentPlugin paymentPlugin = sysPluginService.getPaymentPlugin(sysPlugin.getPluginId());

        Member member = memberService.selectByPrimaryKey(refunds.getMemberId());
        if (member==null) {
            return CommResult.error("无效注册会员");
        }
        SysUser sysUser = sysUserService.findById(member.getUserId());
        if (sysUser==null) {
            return CommResult.error("无效注册用户");
        }

        Payment payment = paymentService.findById(refunds.getPaymentId());

        Map<String,Object> resultMap = paymentPlugin.refund(sysPlugin,sn,payment.getSn(),payment.getAmount(),refunds.getAmount(),request);

        try {

            if ("0000".equals(resultMap.get("return_code").toString())) {
                refundsService.handle(sn,resultMap.get("return_code").toString());
            }

            if ("0003".equals(resultMap.get("return_code").toString())) {
                refundsService.failure(sn);
            }

            return CommResult.success(resultMap);
        } catch (Exception e) {
            return CommResult.error("通知失败");
        }

    }

}
